package com.baichang.taoshunda.dao.impl;

import com.baichang.framework.dao.impl.BaseDaoImpl;
import com.baichang.framework.model.Page;
import com.baichang.taoshunda.dao.CouponDao;
import com.baichang.taoshunda.entity.Coupon;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by ${wushenglu} on 17/08/23.
 */
@Repository
public class CouponDaoImpl extends BaseDaoImpl<Coupon> implements CouponDao {
    /**
     * 查询商家的优惠活动
     *
     * @param busId
     * @return
     */
    @Override
    public List<Map<String, Object>> getCouponByBussId(int busId) {
        String sql = "SELECT * FROM t_coupon WHERE buss_id=?";
        sql += " AND TO_DAYS(NOW())<=TO_DAYS(receive_end_time) AND TO_DAYS(NOW())>=TO_DAYS(start_time) ORDER BY `min_money`desc ";
        return queryForMapList(sql, busId);
    }

    /**
     * 查看优惠券
     *
     * @param id
     * @param nowPage
     * @param pageSize @return
     */
    @Override
    public Page<Map<String, Object>> examineCoupon(Integer id, int nowPage, int pageSize) {
        String sql = "SELECT * FROM t_coupon WHERE buss_id = ?";
        return pageForBeanList(sql, nowPage, pageSize, id);
    }

    @Override
    public int getCountCoupon(int busId) {
        String sql = "SELECT COUNT(0) FROM `t_coupon`WHERE buss_id=?";
        return queryForInt(sql, busId);
    }

    /**
     * 根据状态查询商家的活动
     *
     * @param bussId 商家编号
     * @param state  状态
     *               0：待生效
     *               1：已生效
     *               2：已结束
     * @return
     */
    @Override
    public List<Map<String, Object>> findCouponByState(Integer bussId, Integer state) {
        List<Object> objs = new ArrayList<Object>();
        String sql = "SELECT *," + state + " state FROM {table} WHERE buss_id=? ";
        objs.add(bussId);
        if (state == 0) {
            sql += "  AND CURTIME()<=start_time ";
        } else if (state == 1) {
            sql += " AND CURTIME()>=start_time AND CURTIME()<=receive_end_time ";
        } else if (state == 2) {
            sql += " AND CURTIME()>=receive_end_time ";
        }
        return queryForMapList(sql, objs.toArray());
    }

    /**
     * 根据商家编号获取商家满减的kid
     *
     * @param bussId 商家编号
     * @return
     */
    @Override
    public List<Map<String, Object>> getCouponKidByBussId(Integer bussId) {
        String sql = " SELECT * FROM t_coupon WHERE buss_id=? GROUP BY coupon_kid ";
        return queryForMapList(sql, bussId);
    }

    @Override
    public List<Coupon> findCouponByKid(String couponKid) {
        String sql = " SELECT * FROM {table} WHERE coupon_kid=? ";
        return queryForBeanList(sql, couponKid);
    }
}
